﻿/*
 * 由SharpDevelop创建。
 * 用户： PC
 * 日期: 2025/7/17
 * 时间: 16:08
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Web.Script.Serialization;

namespace UniteBan
{
	/// <summary>
	/// Description of UserControl1.
	/// </summary>
	public class UniteBan
	{
		static BDSCSBox.DataAdapter handle = null;
		private static UniteBan instance = null;
		
		string HttpGet(string url, string exdata) {
			if (!string.IsNullOrEmpty(exdata))
				url = url + "?" + exdata;
			HttpWebRequest r = (HttpWebRequest)WebRequest.Create(url);
			r.Method = "GET";
			var rp = r.GetResponse();
			var rs = rp.GetResponseStream();
			var rd = new StreamReader(rs, Encoding.UTF8);
			var data = rd.ReadToEnd();
			rd.Close();
			rs.Close();
			rp.Close();
			return data;
		}
		
		public UniteBan()
		{
			BDSCSBox.TYPES.F_FUNC onreceive = (msg) => {
				int i = msg.IndexOf("INFO] Player connected:");
				if (i > 0) {
					var pandx = msg.Substring(i+5);
					var pxs = pandx.Split(',');
					if (pxs.Length == 2) {
						var ps = pxs[0].Split(':');
						var xs = pxs[1].Split(':');
						if (ps.Length == 2 && xs.Length == 2) {
							var pname = ps[1].Trim();
							var xuid = xs[1].Trim();
							Console.Out.WriteLine("[UniteBan] 正准备查询{0}云黑，请稍后……", xuid);
							string url = "https://uniteban.mcwaf.cn/api.php?xuid=" + xuid;
							try {
								var r = HttpGet(url, null);
								var ser = new JavaScriptSerializer();
								var d = ser.Deserialize<Dictionary<string, object>>(r);
								bool exists =  (bool)d["exists"];
								if (exists) {
									Console.Out.WriteLine("[UniteBan] 已检测出云黑对象，延迟5秒后执行踢出操作");
									new Thread(()=>{
									           	Thread.Sleep(5000);
									           	handle.sendMsg("kick \"" + pname + "\" Kicked by UniteBan list.");
									           }).Start();
								}
							} catch(Exception e){Console.Out.WriteLine(e.StackTrace);}
						}
					}
				}
				return true;
			};
			handle.addDataReceiver(onreceive);
		}
		
		public static UniteBan getInstance(BDSCSBox.DataAdapter h) {
			handle = h;
			instance = new UniteBan();
			return instance;
		}
	}
}

namespace BDSCSBox {
	public class CSL {
		public bool onStart(BDSCSBox.DataAdapter handle) {	// dll入口，注册所有函数
			UniteBan.UniteBan.getInstance(handle);
			Console.WriteLine("[UniteBan] 联合封禁（云黑）已加载，详情查看 https://uniteban.mcwaf.cn/");
			return true;
		}
	}
}